package com.zzyl.nursing.service.impl;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.AIModelInvoker;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.vo.health.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 * 
 * @author zhai
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AIModelInvoker aiModelInvoker;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessment healthAssessment)
    {
        //1.智能分析，设计Prompt，根据身份证号读取Redis中的体检内容(组装Prompt)
        String prompt = getPrompt(healthAssessment.getIdCard());

        //2.调用千帆大模型，评测体检报告(返回分析结果，JSON格式)
        String content = aiModelInvoker.qianfanInvoker(prompt);
        if (StringUtils.isEmpty(content)){
            throw new BaseException("AI分析失败");
        }
        //3.解析评测体检报告数据
        HealthReportVo healthReportVo = JSONUtil.toBean(content, HealthReportVo.class);
        //3.将读取到的体检报告保存到数据库中，并返回结果id
        return inserthealehAssessment(healthReportVo,healthAssessment);
    }

    /**
     * 保存到数据库中
     *
     * @param healthReportVo
     * @param healthAssessment
     * @return
     */
    private Long inserthealehAssessment(HealthReportVo healthReportVo, HealthAssessment healthAssessment) {
        //身份证号码
        String idCard = healthAssessment.getIdCard();
        healthAssessment.setBirthDate(IDCardUtils.getBirthDateByIdCard(idCard));
        healthAssessment.setAge(IDCardUtils.getAgeByIdCard(idCard));
        healthAssessment.setGender(IDCardUtils.getGenderFromIdCard(idCard));
        //获取护理等级分数
        double healthIndex = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthIndex));
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());
        //是否建议入住
        healthAssessment.setSuggestionForAdmission(healthIndex >= 60 ? 0 : 1);
        healthAssessment.setNursingLevelName(getNursingLevelName(healthIndex));
        healthAssessment.setAdmissionStatus(1);
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        healthAssessment.setAssessmentTime(LocalDateTime.now());
        healthAssessment.setReportSummary(healthReportVo.getSummarize());
        healthAssessment.setDiseaseRisk(JSONUtil.toJsonStr(healthReportVo.getRiskDistribution()));
        healthAssessment.setAbnormalAnalysis(JSONUtil.toJsonStr(healthReportVo.getAbnormalData()));
        healthAssessment.setSystemScore(JSONUtil.toJsonStr(healthReportVo.getSystemScore()));
        healthAssessmentMapper.insert(healthAssessment);
        return healthAssessment.getId();


    }

    /**
     * 计算护理等级
     * @param healthIndex
     * @return
     */
    private String getNursingLevelName(double healthIndex) {
        if (healthIndex < 0 || healthIndex > 100){
            throw new BaseException("健康评分异常");
        }
        if (healthIndex >= 90){
            return "特级护理等级";
        }else if (healthIndex < 90 && healthIndex >= 80){
            return "一级护理等级";
        }else if (healthIndex < 80 && healthIndex >= 70){
            return "二级护理等级";
        }else if (healthIndex < 70 && healthIndex >= 60){
            return "三级护理等级";
        }
        return "无";
    }


    /**
     * 组装Prompt
     * @param idCard 身份证号
     * @return      返回Prompt
     */
    private String getPrompt(String idCard) {
        try(

                InputStream is = this.getClass().getClassLoader().getResourceAsStream("prompts\\healthFile.txt");//获取文件流
                InputStreamReader reader = new InputStreamReader(is); // 获取输入流
                BufferedReader br = new BufferedReader(reader);  // 获取缓冲流
                ) {
            //1.获取Redis中的pfd内容
            String content = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT, idCard);
            redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT,idCard);
            StringBuilder sb = new StringBuilder();
            //2.获取文本文档中的内容
            String line;
            while ((line = br.readLine()) != null){
                sb.append(line);
                if (line.contains("体检内容如下：")){
                    sb.append(content);
                }
            }
            String prompt = sb.toString();
            return prompt;
        } catch (IOException e) {
            throw new BaseException("读取文件失败");
        }

    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.deleteById(id);
    }
}
